#!/usr/bin/env ruby

# Copyright (c) 2010-2012 Microsoft Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'rubygems'
require 'ruby-aws'
require 'fileutils'
require 'facets/file'

module MOS

class Config
	WORKING_DIR = File.dirname($0)
	CONFIG_FILE = WORKING_DIR + '/config.txt'

	private_class_method :new
	@@config = nil

	def self.create
		@@config = new unless @@config
		@@config.init
		@@config
	end

	def init
		if File.exist?(CONFIG_FILE)
			@data = Amazon::Util::DataReader.load(CONFIG_FILE, :Properties)
		else
			@data = { }
		end

		init_default(:RequesterName,		'crowdMOS Requester')

		init_default(:HITPropertiesFile,	'MOS.hit_properties')
		init_default(:HITQuestionFile,		'MOS.hit_question')
		init_default(:HITInputFile,		'MOS.hit_input')
		init_default(:HITSuccessFile,		'MOS.hit_success')
		init_default(:HITFailureFile,		'MOS.hit_failure')
		init_default(:HITResultsFile,		'MOS.hit_results')

		init_default(:RewriteIdentifier,	false)
		init_default(:SamplesPerHIT,		0)
		init_default(:MinSampleWorkingTime,	1.0)
		init_default(:BonusMinAssignments,	10)
		init_default(:BonusForQuantity,		0.05)
		init_default(:BonusForQualityTop50Pct,	0.10)
		init_default(:BonusForQualityTop10Pct,	0.10)

		init_default(:ThreadCount,		5)
		init_default(:Server,			:Sandbox)

		self[:RewriteIdentifier] = self[:RewriteIdentifier].to_s.casecmp('true') == 0;
	end

	def save
		if File.exist?(CONFIG_FILE)
			FileUtils.move(CONFIG_FILE, CONFIG_FILE + '.backup')
		end
		Amazon::Util::DataReader.save(CONFIG_FILE, @data, :Properties)
		
		raw_config = File.read(CONFIG_FILE)
		raw_config = raw_config.split("\n")
		raw_config.map! { |line| line.chomp }
		raw_config.sort! { |a, b| a <=> b }
		raw_config = raw_config.join("\r\n")
		File.write(CONFIG_FILE, raw_config)
	end

	def [](key)
		if key.to_s.match('File')
			return WORKING_DIR + '/' + @data[key.to_sym]
		else
			return @data[key.to_sym]
		end
	end

	def []=(key, value)
		return @data[key.to_sym] = value
	end

	def has_key?(key)
		return @data.has_key?(key.to_sym)
	end

	private

	def init_default(key,value)
		if !has_key?(key)
			self[key] = value
		end
	end
end

end # MOS
